package com.flavors.wan.main.model;

import android.text.TextUtils;

import com.flavors.wan.main.bean.UserBean;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.plat.sdk.common.SPUtils;

/**
 * @author Created by ydong on 2020/1/16 12:02
 * @desc: 用户登录数据的保存 退出清除 更新 获取 是否登录状态 获取用户id
 */
public class UserUtils {
    private static final String KEY_LOGIN_BEAN = "KEY_LOGIN_BEAN";
    private UserBean mUserBean;

    private static class Holder {
        private static final UserUtils INSTANCE = new UserUtils();
    }

    public static UserUtils getInstance() {
        return Holder.INSTANCE;
    }

    /**
     * 登录成功后 将用户信息保存到内存中和sp中
     *
     * @param user
     */
    public void login(UserBean user) {
        mUserBean = user;
        String json = new Gson().toJson(user);
        SPUtils.getInstance().save(KEY_LOGIN_BEAN, json);//将bean转为json存到本地
    }

    public void logout() {
        mUserBean = null;
        SPUtils.getInstance().clear();
    }

    public UserBean getUserBean() {
        if (mUserBean == null) {
            String json = SPUtils.getInstance().get(KEY_LOGIN_BEAN, "");
            if (!TextUtils.isEmpty(json)) {
                try {
                    mUserBean = new Gson().fromJson(json, UserBean.class);//将保存到本地的json转化为bean
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }
            }
        }
        return mUserBean;
    }

    public boolean isLogin() {
        UserBean loginBean = getUserBean();
        if (loginBean == null) {
            return false;
        }
        if (loginBean.getId() > 0) {
            return true;
        }
        return false;
    }

    public int getUserId() {
        UserBean loginBean = getUserBean();
        if (loginBean == null) {
            return 0;
        }
        return loginBean.getId();
    }


}
